package com.example.demo.aop.monitor;

import com.example.demo.WeiXinService;
import com.example.demo.httpMessageConvert.Err;
import com.example.demo.httpMessageConvert.weixin.AccessToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * Created by tangxinmao on 2017/3/13.
 */
@Component
@org.aspectj.lang.annotation.Aspect
public class Aspect {
    @Autowired
    private WeiXinService weiXinService;

    private static final Logger logger = LogManager.getLogger(Aspect.class);

    @Pointcut("execution(* com.example.demo.WeiXinService.*(..))")
    public void accessToken() {
    }

    /*   @Before("log()")
       public void testBefore(JoinPoint joinPoint){
           ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
           HttpServletRequest httpServletRequest = requestAttributes.getRequest();
           httpServletRequest.getRequestURI();//url
           httpServletRequest.getMethod();//get post
           httpServletRequest.getRemoteAddr();//ip
           joinPoint.getSignature().getDeclaringTypeName();//类方法
           joinPoint.getArgs();//参数

       }*/
    @AfterThrowing(value = "accessToken()", throwing = "myException")
    public void accessTokenAfterThrowing(JoinPoint joinPoint, MyException myException) throws Throwable {
        if(myException.getCode()==40001){
            AccessToken accessToken = weiXinService.getToken();
            if (accessToken != null)
                ((ProceedingJoinPoint) joinPoint).proceed();
        }
    }
    @AfterReturning(value = "accessToken()", returning = "returnValue")
    public void accessTokenAfterReturning(JoinPoint joinPoint, Err returnValue) throws Throwable {
        if (returnValue!=null&&(returnValue.getErrcode().equals(48001)||returnValue.getErrcode().equals(40001))) {
            AccessToken accessToken = weiXinService.getToken();
            if (accessToken != null)
                ((ProceedingJoinPoint) joinPoint).proceed();
        }

    }
/*    @After("log()")
    public void testAfter(){

    }*/
 /*   @AfterReturning(pointcut = "log()",returning = "object")
    public  void afterReturning(JoinPoint joinPoint,Object object){

    }*/
}
